package com.molichuxing.services.business.service.impl;

import com.molichuxing.framework.exception.BizException;
import com.molichuxing.services.business.convertor.Convert;
import com.molichuxing.services.business.dto.response.*;
import com.molichuxing.services.business.service.*;
import com.molichuxing.services.contants.OrderStatusConst;
import com.molichuxing.services.infrastructure.dto.response.*;
import com.molichuxing.services.infrastructure.service.*;
import com.molichuxing.services.property.LawsuitStateEnum;
import com.molichuxing.services.property.OrderExclusivelStatusEnum;
import com.molichuxing.services.property.OrderSubscribeStatusEnum;
import com.molichuxing.services.property.OrderTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * C端用户订单组合服务
 *
 * @author zoumingyu
 * @date 2019年8月22日
 */
@Service("orderBizService")
public class OrderBizServiceImpl implements OrderBizService {
    private static final Logger logger = LoggerFactory.getLogger(OrderBizServiceImpl.class);

    @Resource
    private OrderService orderService;

    @Resource
    private OrderDealerService orderDealerService;

    @Resource
    private OrderSubscribeService orderSubscribeService;

    @Resource
    private OrderExclusivelService orderExclusivelService;

    @Resource
    private OrderMileageService orderMileageService;

    @Resource
    private OrderSubscribeBizService orderSubscribeBizService;

    @Resource
    private OrderExclusivelBizService orderExclusivelBizService;

    @Resource
    private OrderAuditService orderAuditService;

    @Resource
    private OrderSubscribeSettlementService orderSubscribeSettlementService;

    @Resource
    private OrderGuarantorService orderGuarantorService;

    @Resource
    private OrderDeliveryService orderDeliveryService;

    @Resource
    private OrderPurchaseBizService orderPurchaseBizService;

    @Resource
    private OrderReturnService orderReturnService;

    @Resource
    private LawsuitService lawsuitService;

    @Resource
    private OrderRenegeBizService orderRenegeBizService;

    /**
     * 根据用户id查询订单信息
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public List<UserOrderBizDto> getOrderByUser(Integer userId) {
        List<UserOrderBizDto> result = new ArrayList<>();
        // 根据用户id查询专属里程订单
        List<UserOrderBizDto> exclusivelList = orderExclusivelBizService.getOrderExclusivelByUser(userId);
        if (exclusivelList != null && exclusivelList.size() > 0) {
            result.addAll(exclusivelList);
        }
        // 根据用户id查询订阅里程订单
        List<UserOrderBizDto> subscribeList = orderSubscribeBizService.getOrderSubscribeByUser(userId);
        if (subscribeList != null && subscribeList.size() > 0) {
            result.addAll(subscribeList);
        }
        // 判断是否存在订单
        if (result == null || result.size() <= 0) {
            return null;
        }
        // 按下单时间倒序
        result = result.stream().sorted(Comparator.comparing(UserOrderBizDto::getOrderTime).reversed())
                .collect(Collectors.toList());

        return result;
    }

    /**
     * 根据用户id查询首页是否需要显示订单信息
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public Boolean getHasPageHomeOrderByUser(Integer userId) {
        boolean result = false;
        // 根据用户id查询专属里程订单
        List<OrderExclusivelDto> exclusivelList = orderExclusivelService.getNormalByUser(userId);
        if (exclusivelList != null && exclusivelList.size() > 0) {
            for (OrderExclusivelDto orderExclusivelDto : exclusivelList) {
                if (OrderExclusivelStatusEnum.TRADE_USE.equals(orderExclusivelDto.getOrderStatus()) ||
                        OrderExclusivelStatusEnum.RENEGE_ACCEPTED.equals(orderExclusivelDto.getOrderStatus()) ||
                        OrderExclusivelStatusEnum.RENEGE_SETTLEMENT.equals(orderExclusivelDto.getOrderStatus()) ||
                        OrderExclusivelStatusEnum.RENEGE_REFUND.equals(orderExclusivelDto.getOrderStatus()) ||
                        OrderExclusivelStatusEnum.RENEGE_UNPAID.equals(orderExclusivelDto.getOrderStatus())) {
                    if (orderExclusivelDto.getCarId() != null && orderExclusivelDto.getCarId() > 0) {
                        result = true;
                        break;
                    }
                }
            }
        }
        if (result) {
            return result;
        }
        // 根据用户id查询订阅里程订单
        List<OrderSubscribeDto> subscribeList = orderSubscribeService.getNormalByUser(userId);
        if (subscribeList != null && subscribeList.size() > 0) {
            for (OrderSubscribeDto orderSubscribeDto : subscribeList) {
                if (OrderSubscribeStatusEnum.TRADE_USE.equals(orderSubscribeDto.getOrderStatus())) {
                    result = true;
                    break;
                }
            }
        }

        return result;
    }

    /**
     * 根据用户id查询是否正常订单信息（不查询取消、删除订单）
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public Boolean getHasNormalOrderByUser(Integer userId) {
        // 根据用户id查询专属里程订单
        List<OrderExclusivelDto> exclusivelList = orderExclusivelService.getNormalByUser(userId);
        if (exclusivelList != null && exclusivelList.size() > 0) {
            return true;
        }
        // 根据用户id查询订阅里程订单
        List<OrderSubscribeDto> subscribeList = orderSubscribeService.getNormalByUser(userId);
        if (subscribeList != null && subscribeList.size() > 0) {
            return true;
        }

        return false;
    }

    /**
     * 根据用户id查询正常订单信息（不查询取消、删除订单）
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public List<OrderMemberBizDto> getNormalOrderByUser(Integer userId) {
        List<OrderMemberBizDto> result = new ArrayList<>();
        // 根据用户id查询专属里程订单
        List<OrderExclusivelDto> exclusivelList = orderExclusivelService.getNormalByUser(userId);
        if (exclusivelList != null && exclusivelList.size() > 0) {
            for (OrderExclusivelDto orderExclusivelDto : exclusivelList) {
                OrderExclusivelBizDto bizDto = Convert.toOrderExclusivelBizDto(orderExclusivelDto);
                // 判断是否退租
                if (OrderStatusConst.RENEGE_EXCLUSIVEL_STATUS.contains(orderExclusivelDto.getOrderStatus())) {
                    // 查询退租信息
                    bizDto.setRenege(orderRenegeBizService.getOrderRenege(orderExclusivelDto.getOrderCode(),
                            orderExclusivelDto.getUserId()));
                } else if (OrderExclusivelStatusEnum.LAWSUIT.equals(orderExclusivelDto.getOrderStatus())) {
                    // 查询诉讼信息
                    bizDto.setLawsuit(lawsuitService.getLawsuit(orderExclusivelDto.getOrderCode()));
                }

                result.add(bizDto);
            }
        }
        // 根据用户id查询订阅里程订单
        List<OrderSubscribeDto> subscribeList = orderSubscribeService.getNormalByUser(userId);
        if (subscribeList != null && subscribeList.size() > 0) {
            // 判断订单状态，订单查询结算信息
            for (OrderSubscribeDto orderSubscribeDto : subscribeList) {
                OrderSubscribeBizDto orderSubscribeBizDto = convert(orderSubscribeDto);
                if (OrderSubscribeStatusEnum.RETURN_UNPAID.equals(orderSubscribeDto.getOrderStatus())) {
                    // 待缴费订单，查询缴费信息
                    OrderSubscribeSettlementDto orderSubscribeSettlementDto = orderSubscribeSettlementService
                            .getOrderSubscribeSettlement(orderSubscribeDto.getOrderCode());
                    orderSubscribeBizDto.setSettlementFee(
                            orderSubscribeSettlementDto == null ? null : orderSubscribeSettlementDto.getTotalFee());
                }
                result.add(orderSubscribeBizDto);
            }
        }
        // 判断是否存在订单
        if (result == null || result.size() <= 0) {
            return null;
        }
        // 按下单时间倒序
        result = result.stream().sorted(Comparator.comparing(OrderMemberBizDto::getOrderTime).reversed())
                .collect(Collectors.toList());

        return result;
    }

    /**
     * 订阅里程dto转换并查询加购信息
     *
     * @param orderSubscribeDto
     * @return
     */
    private OrderSubscribeBizDto convert(OrderSubscribeDto orderSubscribeDto) {
        OrderSubscribeBizDto result = Convert.toOrderSubscribeBizDto(orderSubscribeDto);
        OrderPurchaseBizDto orderPurchaseBizDto = orderPurchaseBizService.getOrderPurchase(result.getOrderCode());
        if (orderPurchaseBizDto == null) {
            return result;
        }
        result.setPurchaseMileage(orderPurchaseBizDto.getTotalPurchaseMileage());
        result.setPurchaseFee(orderPurchaseBizDto.getTotalPurchaseFee());
        result.setBeyondMileage(orderPurchaseBizDto.getTotalBeyondMileage());
        result.setBeyondFee(orderPurchaseBizDto.getTotalBeyondFee());

        return result;
    }

    /**
     * 根据车辆id查询订单信息
     *
     * @param carId 车辆id
     * @return
     */
    @Override
    public List<CarOrderBizDto> getOrderByCar(Integer carId) {
        List<CarOrderBizDto> result = new ArrayList<>();
        // 根据用户id查询专属里程订单
        List<CarOrderBizDto> exclusivelList = orderExclusivelBizService.getOrderExclusivelByCar(carId);
        if (exclusivelList != null && exclusivelList.size() > 0) {
            result.addAll(exclusivelList);
        }
        // 根据用户id查询订阅里程订单
        List<CarOrderBizDto> subscribeList = orderSubscribeBizService.getOrderSubscribeByCar(carId);
        if (subscribeList != null && subscribeList.size() > 0) {
            result.addAll(subscribeList);
        }
        // 判断是否存在订单
        if (result == null || result.size() <= 0) {
            return null;
        }
        // 按下单时间倒序
        result = result.stream().sorted(Comparator.comparing(CarOrderBizDto::getOrderTime).reversed())
                .collect(Collectors.toList());
        // 查询提车、还车信息
        for (CarOrderBizDto carOrderBizDto : result) {
            // 查询提车信息
            OrderDeliveryDto orderDeliveryDto = orderDeliveryService.getOrderDelivery(carOrderBizDto.getOrderCode());
            carOrderBizDto.setDeliveryStoreId(carOrderBizDto.getPlaceStoreId());
            if (orderDeliveryDto != null) {
                carOrderBizDto.setDeliveryStoreId(orderDeliveryDto.getStoreId());
                carOrderBizDto.setDeliveryTime(orderDeliveryDto.getDeliveryTime());
            }
            // 查询还车信息
            OrderReturnDto orderReturnDto = orderReturnService.getOrderReturn(carOrderBizDto.getOrderCode());
            if (orderReturnDto != null) {
                carOrderBizDto.setReturnTime(orderReturnDto.getReturnTime());
            }
        }

        return result;
    }

    /**
     * 查询订单信息
     *
     * @param carIds 车辆ids
     * @return
     */
    @Override
    public Map<Integer, List<CarOrderBizDto>> getOrderByCar(List<Integer> carIds) {
        Map<Integer, List<CarOrderBizDto>> result = null;
        if (carIds == null || carIds.isEmpty()) {
            return result;
        }
        result = new HashMap<>();
        for (Integer carId : carIds) {
            List<CarOrderBizDto> orders = this.getOrderByCar(carId);
            if (orders == null || orders.isEmpty()) {
                continue;
            }

            result.put(carId, orders);
        }

        return result.isEmpty() ? null : result;
    }

    /**
     * 根据车辆id查询订单信息
     *
     * @param carId    车辆id
     * @param storeIds 门店ids
     * @return
     */
    @Override
    public List<CarOrderBizDto> getOrderByCar(Integer carId, List<Integer> storeIds) {
        List<CarOrderBizDto> result = new ArrayList<>();
        // 根据用户id查询专属里程订单
        List<CarOrderBizDto> exclusivelList = orderExclusivelBizService.getOrderExclusivelByCar(carId, storeIds);
        if (exclusivelList != null && exclusivelList.size() > 0) {
            result.addAll(exclusivelList);
        }
        // 根据用户id查询订阅里程订单
        List<CarOrderBizDto> subscribeList = orderSubscribeBizService.getOrderSubscribeByCar(carId, storeIds);
        if (subscribeList != null && subscribeList.size() > 0) {
            result.addAll(subscribeList);
        }
        // 判断是否存在订单
        if (result == null || result.size() <= 0) {
            return null;
        }
        // 按下单时间倒序
        result = result.stream().sorted(Comparator.comparing(CarOrderBizDto::getOrderTime).reversed())
                .collect(Collectors.toList());

        // 查询提车、还车信息
        for (CarOrderBizDto carOrderBizDto : result) {
            // 查询提车信息
            OrderDeliveryDto orderDeliveryDto = orderDeliveryService.getOrderDelivery(carOrderBizDto.getOrderCode());
            carOrderBizDto.setDeliveryStoreId(carOrderBizDto.getPlaceStoreId());
            if (orderDeliveryDto != null) {
                carOrderBizDto.setDeliveryStoreId(orderDeliveryDto.getStoreId());
                carOrderBizDto.setDeliveryTime(orderDeliveryDto.getDeliveryTime());
            }
            // 查询还车信息
            OrderReturnDto orderReturnDto = orderReturnService.getOrderReturn(carOrderBizDto.getOrderCode());
            if (orderReturnDto != null) {
                carOrderBizDto.setReturnTime(orderReturnDto.getReturnTime());
            }
        }

        return result;
    }

    /**
     * 查询用车中订单信息
     *
     * @param carId  车辆id
     * @param userId 用户id
     * @return
     */
    @Override
    public CarOrderBizDto getUseOrderByCar(Integer carId, Integer userId) {
        CarOrderBizDto result = null;
        // 根据车辆id查询专属里程订单
        List<CarOrderBizDto> exclusivelList = orderExclusivelBizService.getOrderExclusivelByCar(carId);
        if (exclusivelList != null && exclusivelList.size() > 0) {
            for (CarOrderBizDto carOrderBizDto : exclusivelList) {
                OrderExclusivelStatusEnum orderStatus = (OrderExclusivelStatusEnum) carOrderBizDto.getOrderStatus();
                if (OrderExclusivelStatusEnum.TRADE_USE.equals(orderStatus)) {
                    if (userId == null) {
                        result = carOrderBizDto;
                        break;
                    } else if (carOrderBizDto.getUserId().equals(userId)) {
                        result = carOrderBizDto;
                        break;
                    }
                }
            }
        }
        if (result != null) {
            // 查询提车信息
            OrderDeliveryDto orderDeliveryDto = orderDeliveryService.getOrderDelivery(result.getOrderCode());
            result.setDeliveryStoreId(result.getPlaceStoreId());
            if (orderDeliveryDto != null) {
                result.setDeliveryStoreId(orderDeliveryDto.getStoreId());
                result.setDeliveryTime(orderDeliveryDto.getDeliveryTime());
            }
            return result;
        }

        // 根据用户id查询订阅里程订单
        List<CarOrderBizDto> subscribeList = orderSubscribeBizService.getOrderSubscribeByCar(carId);
        if (subscribeList != null && subscribeList.size() > 0) {
            for (CarOrderBizDto carOrderBizDto : subscribeList) {
                OrderSubscribeStatusEnum orderStatus = (OrderSubscribeStatusEnum) carOrderBizDto.getOrderStatus();
                if (OrderSubscribeStatusEnum.TRADE_USE.equals(orderStatus)) {
                    if (userId == null) {
                        result = carOrderBizDto;
                        break;
                    } else if (carOrderBizDto.getUserId().equals(userId)) {
                        result = carOrderBizDto;
                        break;
                    }
                }
            }
        }
        if (result != null) {
            // 查询提车信息
            OrderDeliveryDto orderDeliveryDto = orderDeliveryService.getOrderDelivery(result.getOrderCode());
            result.setDeliveryStoreId(result.getPlaceStoreId());
            if (orderDeliveryDto != null) {
                result.setDeliveryStoreId(orderDeliveryDto.getStoreId());
                result.setDeliveryTime(orderDeliveryDto.getDeliveryTime());
            }
        }

        return result;
    }

    /**
     * 查询用车中订单信息
     *
     * @param carIds 车辆ids
     * @return
     */
    @Override
    public Map<Integer, CarOrderBizDto> getUseOrderByCar(List<Integer> carIds) {
        Map<Integer, CarOrderBizDto> result = null;
        if (carIds == null || carIds.isEmpty()) {
            return result;
        }
        result = new HashMap<>();
        for (Integer carId : carIds) {
            CarOrderBizDto carOrderBizDto = this.getUseOrderByCar(carId, null);
            if (carOrderBizDto == null) {
                continue;
            }
            result.put(carId, carOrderBizDto);
        }

        return result.isEmpty() ? null : result;
    }

    /**
     * 根据订单号获取订单信息
     *
     * @param orderCode 订单号
     * @return
     */
    @Override
    public OrderBizDto getOrder(Long orderCode) {
        OrderBizDto result = null;
        OrderDto orderDto = orderService.getOrder(orderCode);
        if (orderDto == null) {
            return result;
        }
        result = Convert.toOrderBizDto(orderDto);
        // 判断订单类型
        if (OrderTypeEnum.EXCLUSIVEL.equals(orderDto.getType())) {
            // 专属里程订单
            OrderExclusivelDto orderExclusivelDto = orderExclusivelService.getOrderExclusivel(orderCode);
            result = Convert.toOrderExclusivelBizDto(orderExclusivelDto);
            result.setType(OrderTypeEnum.EXCLUSIVEL);
        } else if (OrderTypeEnum.SUBSCRIBE.equals(orderDto.getType())) {
            // 订阅里程订单
            OrderSubscribeDto orderSubscribeDto = orderSubscribeService.getOrderSubscribe(orderCode);
            result = Convert.toOrderSubscribeBizDto(orderSubscribeDto);
            result.setType(OrderTypeEnum.SUBSCRIBE);
        } else if (OrderTypeEnum.RELET_MILEAGE.equals(orderDto.getType())) {
            OrderMileageDto orderMileageDto = orderMileageService.getOrderMileage(orderCode);
            result = Convert.toOrderMileageBizDto(orderMileageDto);
            result.setType(OrderTypeEnum.RELET_MILEAGE);
        } else if (OrderTypeEnum.DEALER.equals(orderDto.getType())) {
            // 经销商订单
            OrderDealerDetailBasicDto orderDealerDetailBasicDto = orderDealerService.getDetailBasic(orderCode);
            result.setDealerId(orderDealerDetailBasicDto.getDealerId());
            result.setType(OrderTypeEnum.DEALER);
        }

        return result;
    }

    /**
     * 根据订单号获取订单信息
     *
     * @param orderCodes 订单号
     * @return
     */
    @Override
    public Map<Long, OrderBizDto> getOrder(List<Long> orderCodes) {
        Map<Long, OrderBizDto> result = null;
        if (orderCodes == null || orderCodes.isEmpty()) {
            return result;
        }

        result = new HashMap<>();
        for (Long orderCode : orderCodes) {
            OrderBizDto OrderBizDto = this.getOrder(orderCode);
            if (OrderBizDto == null) {
                continue;
            }
            result.put(orderCode, OrderBizDto);
        }

        return result;
    }

    /**
     * 根据用户id查询订单号
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public List<Long> getOrderCodeByUser(Integer userId) {
        List<Long> result = new ArrayList<>();

        // 查询专属里程订单
        List<Long> orderExclusivelCodes = orderExclusivelService.getOrderCodeByUser(userId);
        if (orderExclusivelCodes != null && !orderExclusivelCodes.isEmpty()) {
            result.addAll(orderExclusivelCodes);
        }
        // 查询订阅里程订单
        List<Long> orderSubscribeCodes = orderSubscribeService.getOrderCodeByUser(userId);
        if (orderSubscribeCodes != null && !orderSubscribeCodes.isEmpty()) {
            result.addAll(orderSubscribeCodes);
        }

        return result.isEmpty() ? null : result;
    }

    /**
     * 根据用户id查询订单号
     *
     * @param userIds 用户id
     * @return
     */
    @Override
    public List<Long> getOrderCodeByUser(List<Integer> userIds) {
        List<Long> result = new ArrayList<>();

        // 查询专属里程订单
        List<Long> orderExclusivelCodes = orderExclusivelService.getOrderCodeByUser(userIds);
        if (orderExclusivelCodes != null && !orderExclusivelCodes.isEmpty()) {
            result.addAll(orderExclusivelCodes);
        }
        // 查询订阅里程订单
        List<Long> orderSubscribeCodes = orderSubscribeService.getOrderCodeByUser(userIds);
        if (orderSubscribeCodes != null && !orderSubscribeCodes.isEmpty()) {
            result.addAll(orderSubscribeCodes);
        }

        return result.isEmpty() ? null : result;
    }

    /**
     * 根据用户id查询所有状态为用车中的车辆id
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public List<OrderCarInfoAppDto> getCarIdsByUser(Integer userId, Integer orderStatus) {
        List<OrderCarInfoAppDto> result = new ArrayList<>();
        OrderCarInfoAppDto orderCarInfoAppDto = null;
        // 根据用户id查询专属里程订单
        List<OrderCarInfoAppDto> exclusiveCarIdList = orderExclusivelBizService.getOrderExclusivelCarIdByUser(userId,
                orderStatus);
        if (exclusiveCarIdList != null && exclusiveCarIdList.size() > 0) {
            for (OrderCarInfoAppDto exclusiveOrderCarInfoAppDto : exclusiveCarIdList) {
                orderCarInfoAppDto = new OrderCarInfoAppDto();
                BeanUtils.copyProperties(exclusiveOrderCarInfoAppDto, orderCarInfoAppDto);
                OrderDeliveryBizDto orderDeliveryBizDto = getDelivery(exclusiveOrderCarInfoAppDto.getOrderCode());
                if (null != orderDeliveryBizDto && null != orderDeliveryBizDto.getDeliveryTime()) {
                    orderCarInfoAppDto.setDeliveryTime(orderDeliveryBizDto.getDeliveryTime());
                }
                result.add(orderCarInfoAppDto);
            }
        }
        // 根据用户id查询订阅里程订单
        List<OrderCarInfoAppDto> subscribeCarIdList = orderSubscribeBizService.getOrderSubscribeCarIdByUser(userId,
                orderStatus);
        if (subscribeCarIdList != null && subscribeCarIdList.size() > 0) {
            for (OrderCarInfoAppDto subscribeOrderCarInfoAppDto : subscribeCarIdList) {
                orderCarInfoAppDto = new OrderCarInfoAppDto();
                BeanUtils.copyProperties(subscribeOrderCarInfoAppDto, orderCarInfoAppDto);
                OrderDeliveryDto subscribeOrderDeliveryDto = orderDeliveryService.getOrderDelivery(subscribeOrderCarInfoAppDto.getOrderCode());
                if (null != orderCarInfoAppDto && null != orderCarInfoAppDto.getDeliveryTime()) {
                    orderCarInfoAppDto.setDeliveryTime(orderCarInfoAppDto.getDeliveryTime());
                } else {
                    Long masterOrderCode = getMasterOrderCode(subscribeOrderCarInfoAppDto.getOrderCode(), OrderTypeEnum.SUBSCRIBE);
                    OrderDeliveryBizDto orderDeliveryBizDto = getDelivery(subscribeOrderCarInfoAppDto.getOrderCode());
                    if (null != orderDeliveryBizDto && null != orderDeliveryBizDto.getDeliveryTime()) {
                        orderCarInfoAppDto.setDeliveryTime(orderDeliveryBizDto.getDeliveryTime());
                    }
                }
                result.add(orderCarInfoAppDto);
            }
        }
        // 判断是否存在用车中的车辆id
        if (result == null || result.size() <= 0) {
            return null;
        }
        return result;
    }

    /**
     * 统计排序订单商品销量
     *
     * @return
     */
    @Override
    public List<Integer> getStatisticsGoods() {
        List<Integer> result = null;
        // 专属订单
        List<Map<String, Object>> temps = orderExclusivelService.getStatisticsGoods();
        // 订阅订单
        temps.addAll(orderSubscribeService.getStatisticsGoods());
        // 排序
        result = temps.stream()
                .sorted(Comparator.comparing((Map<String, Object> map) -> Integer.valueOf(map.get("num").toString()))
                        .reversed())
                .map((Map<String, Object> map) -> Integer.valueOf(map.get("goodsId").toString()))
                .collect(Collectors.toList());
        return result;
    }

    /**
     * 订单是否能下单验证
     *
     * @param userId      用户id
     * @param guarantorId 担保人id
     * @return
     */
    @Override
    public OrderVerifyBizDto orderVerify(Integer userId, Integer guarantorId) {
        OrderVerifyBizDto result = new OrderVerifyBizDto();
        result.setIsGuarantorOrder(false);
        result.setIsOrder(false);

        List<OrderExclusivelStatusEnum> exclusivels = Arrays.asList(OrderExclusivelStatusEnum.TRADE_CANCELED,
                OrderExclusivelStatusEnum.TRADE_FINISH, OrderExclusivelStatusEnum.RENEGE_FINISH);
        List<OrderSubscribeStatusEnum> subscribes = Arrays.asList(OrderSubscribeStatusEnum.TRADE_CANCELED,
                OrderSubscribeStatusEnum.TRADE_FINISH, OrderSubscribeStatusEnum.RETURN_FINISH);

        // 判断是否存在担保人订单
        if (guarantorId != null) {
            Long orderCode = orderGuarantorService.getOrderCode(guarantorId);
            if (orderCode != null) {
                // 查询订单信息
                OrderExclusivelDto orderExclusivelDto = orderExclusivelService.getOrderExclusivel(orderCode);
                if (orderExclusivelDto != null
                        && !exclusivels.contains(orderExclusivelDto.getOrderStatus())) {
                    result.setIsGuarantorOrder(true);
                }
            }
        }

        // 根据用户id查询专属订单信息
        List<OrderExclusivelDto> exclusivelDtos = orderExclusivelService.getOrderListByUser(userId);
        if (exclusivelDtos != null && !exclusivelDtos.isEmpty()) {
            for (OrderExclusivelDto exclusivelDto : exclusivelDtos) {
                // 判断是否存在诉讼订单
                if (OrderExclusivelStatusEnum.LAWSUIT.equals(exclusivelDto.getOrderStatus())) {
                    // 查询诉讼信息
                    LawsuitDto lawsuit = lawsuitService.getLawsuit(exclusivelDto.getOrderCode());
                    if (LawsuitStateEnum.PROGRESS.getValue() == lawsuit.getLawsuitState()) {
                        result.setIsOrder(true);
                        break;
                    }
                } else if (!exclusivels.contains(exclusivelDto.getOrderStatus())) {
                    result.setIsOrder(true);
                    break;
                }
            }
        }
        if (!result.getIsOrder()) {
            // 根据用户id查询订阅里程订单
            List<OrderSubscribeDto> subscribeDtos = orderSubscribeService.getOrderListByUser(userId);
            if (subscribeDtos != null && !subscribeDtos.isEmpty()) {
                for (OrderSubscribeDto subscribeDto : subscribeDtos) {
                    if (!subscribes.contains(subscribeDto.getOrderStatus())) {
                        result.setIsOrder(true);
                        break;
                    }
                }
            }
        }

        return result;
    }


    /**
     * 订单待处理数量
     *
     * @return
     */
    @Override
    public OrderPendCountDto getOrderPendCountDto() {

        OrderPendCountDto orderPendCountDto = new OrderPendCountDto();

        //订阅订单待审核
        orderPendCountDto.setSubscribeReviewed(orderSubscribeService.getOrderSubscribePendCount());

        //专属订单待审核
        orderPendCountDto.setExclusiveReviewed(orderExclusivelService.getOrderExclusivelPendCount());

        return orderPendCountDto;
    }

    /**
     * 续订、加购订单查询最初主订单号（如本身为最初主订单，则返回本身订单号；如订单号查询不到订单，返回null）
     *
     * @param orderCode 订单号(续订传续订订单号，加购传加购订单号)
     * @param orderType 订单类型
     * @return
     */
    @Override
    public Long getMasterOrderCode(Long orderCode, OrderTypeEnum orderType) {
        OrderSubscribeDto orderSubscribeDto = null;
        if (OrderTypeEnum.SUBSCRIBE.equals(orderType)) {
            // 根据订单号查询订单信息
            orderSubscribeDto = orderSubscribeService.getOrderSubscribe(orderCode);
        } else if (OrderTypeEnum.RELET_MILEAGE.equals(orderType)) {
            // 根据订单号查询加购订单信息
            OrderMileageDto orderMileageDto = orderMileageService.getOrderMileage(orderCode);
            if (orderMileageDto == null) {
                return null;
            }
            orderSubscribeDto = orderSubscribeService.getOrderSubscribe(orderMileageDto.getMasterOrderCode());
        }
        // 判断
        if (orderSubscribeDto == null) {
            return orderCode;
        } else if (orderSubscribeDto.getParentOrderCode() != null && orderSubscribeDto.getParentOrderCode() > 0L
                && !orderSubscribeDto.getParentOrderCode().equals(orderCode)) {
            return getMasterOrderCode(orderSubscribeDto.getParentOrderCode(), OrderTypeEnum.SUBSCRIBE);
        }
        return orderSubscribeDto.getOrderCode();
    }

    /**
     * 根据支付日期查询未提车订单信息
     *
     * @param payDate 支付日期
     * @return
     */
    @Override
    public List<OrderMemberBizDto> getUnDeliveryByPayDate(LocalDate payDate) {
        List<OrderMemberBizDto> result = new ArrayList<>();
        // 查询专属里程订单
        List<OrderExclusivelDto> exclusivels = orderExclusivelService.getExclusivel(payDate,
                OrderExclusivelStatusEnum.TRADE_UNDELIVERY);
        if (exclusivels != null && !exclusivels.isEmpty()) {
            result.addAll(Convert.toOrderExclusivelBizDto(exclusivels));
        }
        // 查询订阅里程订单
        List<OrderSubscribeDto> subscribes = orderSubscribeService.getSubscribe(payDate,
                OrderSubscribeStatusEnum.TRADE_UNDELIVERY);
        if (subscribes != null && !subscribes.isEmpty()) {
            result.addAll(Convert.toOrderExclusivelBizDto(exclusivels));
        }
        // 判断是否存在订单
        if (result == null || result.isEmpty()) {
            return null;
        }

        return result;
    }

    /**
     * 根据订单号获取交车信息
     *
     * @param orderCode
     * @return
     */
    @Override
    public OrderDeliveryBizDto getDelivery(Long orderCode) {
        OrderDeliveryBizDto result = null;
        OrderDto orderDto = orderService.getOrder(orderCode);
        if (orderDto == null) {
            return result;
        }

        if (OrderTypeEnum.EXCLUSIVEL.equals(orderDto.getType())) {
            // 专属里程订单，查询提车信息
            result = Convert.toOrderDeliveryBizDto(orderDeliveryService.getOrderDelivery(orderCode));
        } else if (OrderTypeEnum.SUBSCRIBE.equals(orderDto.getType())) {
            // 订阅里程订单
            Long parentOrderCode = this.getMasterOrderCode(orderCode, OrderTypeEnum.SUBSCRIBE);
            result = Convert.toOrderDeliveryBizDto(orderDeliveryService.getOrderDelivery(parentOrderCode));
        } else if (OrderTypeEnum.RELET_MILEAGE.equals(orderDto.getType())) {
            // 加购订单
            Long parentOrderCode = this.getMasterOrderCode(orderCode, OrderTypeEnum.RELET_MILEAGE);
            result = Convert.toOrderDeliveryBizDto(orderDeliveryService.getOrderDelivery(parentOrderCode));
        }

        return result;
    }

    /**
     * 查询每个车型下生效订单（提车、续订支付）数量
     *
     * @return
     */
    @Override
    public Map<Integer, Integer> getEffectiveOrderVehicleStatistics() {
        // 查询已提车的专属订单
        Map<Integer, Integer> exclusivelVehicleMap = orderExclusivelService.getEffectiveOrderVehicleStatistics();
        // 查询已提车的订阅订单
        Map<Integer, Integer> subscribeVehicleMap = orderSubscribeService.getEffectiveOrderVehicleStatistics();
        if ((exclusivelVehicleMap == null || exclusivelVehicleMap.isEmpty())
                && (subscribeVehicleMap == null || subscribeVehicleMap.isEmpty())) {
            // 不存在
            return null;
        }
        Map<Integer, Integer> result = exclusivelVehicleMap == null ? new HashMap<>() : exclusivelVehicleMap;
        // 合并，如果 key（车型id）相同，则 value（数量）累加
        subscribeVehicleMap.forEach((key, value) -> {
            result.merge(key, value, Integer::sum);
        });

        return result;
    }

    /**
     * 查询每个门店下生效订单（提车、续订生效）数量
     *
     * @return
     */
    @Override
    public Map<Integer, Integer> getEffectiveOrderStoreStatistics() {
        // 查询专属订单生效订单
        Map<Integer, Integer> exclusivelStoreMap = orderExclusivelService.getEffectiveOrderStoreStatistics();
        // 询订阅订单生效订单
        Map<Integer, Integer> subscribeStoreMap = orderSubscribeService.getEffectiveOrderStoreStatistics();

        Map<Integer, Integer> result = exclusivelStoreMap == null ? new HashMap<>() : exclusivelStoreMap;
        if (subscribeStoreMap != null && !subscribeStoreMap.isEmpty()) {
            // 合并，如果 key（门店id）相同，则 value（数量）累加
            subscribeStoreMap.forEach((key, value) -> {
                result.merge(key, value, Integer::sum);
            });
        }

        return result.isEmpty() ? null : result;
    }

    /**
     * 查询每个商品下支付订单（支付、续订支付）数量
     *
     * @param orderType 订单类型
     * @return
     */
    @Override
    public List<GoodsSalesStatisticsBizDto> getEffectiveOrderGoodsStatistics(OrderTypeEnum orderType) {
        List<GoodsSalesStatisticsBizDto> result = null;
        // 判断查询类型
        if (OrderTypeEnum.EXCLUSIVEL.equals(orderType)) {
            // 专属
            result = orderExclusivelService.getEffectiveOrderGoodsStatistics();
        } else if (OrderTypeEnum.SUBSCRIBE.equals(orderType)) {
            // 订阅
            result = orderSubscribeService.getEffectiveOrderGoodsStatistics();
        } else {
            // 查询类型错误
            throw new BizException("统计订单类型错误，暂不支持该类型");
        }


        return result;
    }

    /**
     * 查询用户用车订单
     *
     * @param userId   用户id
     * @param isReturn 是否还车 true：已还车订单，false：未还车订单
     * @return 订单号list
     */
    @Override
    public List<Long> getCarOrderCodeByUser(Integer userId, boolean isReturn) {
        List<Long> result = new ArrayList<>();
        // 查询有效专属订单
        List<OrderExclusivelDto> exclusivelList = orderExclusivelService.getNormalByUser(userId);
        if (exclusivelList != null && exclusivelList.size() > 0) {
            for (OrderExclusivelDto dto : exclusivelList) {
                // 判断是否提车
                if (dto.getCarId() == null || dto.getCarId() <= 0) {
                    continue;
                }
                // 是否还车
                if (isReturn) {
                    if (OrderStatusConst.EXCLUSIVEL_RETURN_STATUS.contains(dto.getOrderStatus())) {
                        result.add(dto.getOrderCode());
                    }
                } else {
                    if (OrderStatusConst.EXCLUSIVEL_UNRETURN_STATUS.contains(dto.getOrderStatus())) {
                        result.add(dto.getOrderCode());
                    }
                }
            }
        }
        // 查询有效订阅订单
        List<OrderSubscribeDto> subscribeList = orderSubscribeService.getNormalByUser(userId);
        if (subscribeList != null && subscribeList.size() > 0) {
            for (OrderSubscribeDto dto : subscribeList) {
                // 判断是否提车
                if (dto.getCarId() == null || dto.getCarId() <= 0) {
                    continue;
                }
                // 是否还车
                if (isReturn) {
                    if (OrderStatusConst.SUBSCRIBE_RETURN_STATUS.contains(dto.getOrderStatus())) {
                        result.add(dto.getOrderCode());
                    }
                } else {
                    if (OrderStatusConst.SUBSCRIBE_UNRETURN_STATUS.contains(dto.getOrderStatus())) {
                        result.add(dto.getOrderCode());
                    }
                }
            }
        }

        return result.isEmpty() ? null : result;
    }
}
